package com.hjl.jdbc.dao;

import com.hjl.jdbc.entity.Emp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * @author ServivE
 * @version 0.1
 * @className EmpDaoImpl
 * @description
 * @date 2024/8/7 14:25
 * @since jdk11
 */
@Component("empDao")
public class EmpDaoImpl implements EmpDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public static final RowMapper rowMapper = new RowMapper() {
        @Override
        public Object mapRow(ResultSet resultSet, int i) throws SQLException {
            Emp emp = new Emp();
            int eid = resultSet.getInt("eid");
            String ename = resultSet.getString("ename");
            String esex = resultSet.getString("esex");
            Date hiredate = resultSet.getDate("hiredate");
            String sal = resultSet.getString("sal");
            emp.setEid(eid);
            emp.setEname(ename);
            emp.setEsex(esex);
            emp.setSal(sal);
            emp.setHiredate(hiredate);
            return emp;
        }
    };

    @Override
    public List<Emp> getAllEmps() {
        String sql = "select * from emp";
        List<Emp> list = jdbcTemplate.query(sql, rowMapper);
        return list;
    }

    @Override
    public int addEmp(Emp emp) {
        String sql = "insert into emp(ename,esex,sal) values (?,?,?)";
        Object[] params = {emp.getEname(), emp.getEsex(), emp.getSal()};
        return jdbcTemplate.update(sql, params);
    }

    @Override
    public Emp getEmpById(int eid) {
        String sql = "select * from emp where eid = ?";
        List<Emp> list = jdbcTemplate.query(sql, rowMapper, eid);
        return list.size() > 0 ? list.get(0) : null;
    }
}
